package com.example.backblog.service.blog;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

@Component
public class DistributedLockService {

    @Autowired
    private RedissonClient redissonClient;

    private Redisson redisson;

    @PostConstruct
    private void init() {
        redisson = (Redisson) redissonClient;
    }

    public boolean acquireLock(String lockKey, long expireTime) {
        RLock lock = redisson.getLock(lockKey);
        try {
            return lock.tryLock(expireTime, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }

    public void releaseLock(String lockKey) {
        RLock lock = redisson.getLock(lockKey);
        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }
}
